using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiText.Api.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ApiText.Api.Db;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using ApiText.Api.Params;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using ApiText.Api.Filters;

namespace ApiText.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        //添加一个变量
        readonly string _myAllowcors = "MyAllowcors";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            //配置跨域处理，允许所有来源
            services.AddCors(options =>
            {
                options.AddPolicy(_myAllowcors,
                builder => builder.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin());
            });

            // 注入数据库上下文
            services.AddDbContext<ApiTextDb>(o => o.UseSqlServer());

            // 注入 IRepository接口及其实现类
            services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));



            // 配置token验证的配置内容
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
            {

                //RequireHttpsMetadata 是限定认证操作是否必须通过https来做，这个要跟随项目在生产环境中的运行情况来定，
                //采用对外https，对内http的方式，那这儿可以设为false不使用https 
                option.RequireHttpsMetadata = false;

                option.SaveToken = true;

                var token = Configuration.GetSection("ToKenParameter").Get<ToKenParameter>();


                option.TokenValidationParameters = new TokenValidationParameters
                {
                    //验证发行人的签名
                    ValidateIssuerSigningKey = true,

                    //指定发行人的签名
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(token.Secret)),

                    //指定发行人
                    ValidIssuer = token.Issuer,

                    //验证发行人
                    ValidateIssuer = true,

                    //验证日期
                    ValidateAudience = false
                };

            });


            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(AuditLogActionFilter));
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            //打开认证，用来验证token
            app.UseAuthentication();

            app.UseAuthorization();
             
             //打开自己跨域的请求
              app.UseCors(_myAllowcors);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
